package com.xcity.game.shop.mystery.template;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.xcity.game.common.GameStaticConfig;

import naga.x.game.time.TimeUpdater;
import naga.x.util.TimeUtils;

public class RefreshRule {

	protected long[] time; // 理论刷新点
	protected long endTime;
	protected int probability; // 刷新几率(万分比)
	
	protected MysteryShopRefreshRuleTemplate ref;
	
	private static final Random RND = new Random();
	private static int probabilityFix = 0;
	
	public RefreshRule(MysteryShopRefreshRuleTemplate ref) {
		this.ref = ref;
		this.probability = ref.getProbability() * 100;
		refresh();
	}
	
	public void refresh() {
		long zeroTime = TimeUtils.getTodayZeroTime();
		if (time == null) {
			time = new long[ref.getEndTime() - ref.getStartTime()];
		}
		for (int hour = ref.getStartTime(), i = 0; hour < ref.getEndTime(); hour += 1) {
			time[i++] = zeroTime + TimeUnit.HOURS.toMillis(hour);
		}
		endTime = zeroTime + TimeUnit.HOURS.toMillis(ref.getEndTime());
	}
	
	public long trigger() {
		for (long t : time) {
			if (t >= TimeUpdater.getInstance().now() && RND.nextInt(GameStaticConfig.defaultChanceBase) < probability + probabilityFix) {
				probabilityFix = 0;
				return t;
			}
		}
		probabilityFix += 1000; // 没触发到则增加10%几率
		return 0;
	}
	
	public long getTime(int index) {
		if (index < 0) index = 0;
		else if (index >= time.length) index = time.length - 1;
		return time[index];
	}
	
	public long getEndTime() {
		return endTime;
	}

	public MysteryShopRefreshRuleTemplate getRef() {
		return ref;
	}
	
	@Override
	public String toString() {
		StringBuilder buf = new StringBuilder("TIME[");
		for (long t : time) {
			buf.append(TimeUtils.format(t)).append(',');
		}
		buf.append("]END[").append(TimeUtils.format(endTime)).append("]PRB[").append(probability).append(']');
		return buf.toString();
	}
	
}
